package tomsung.cloud.agdc.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import tomsung.cloud.agdc.bean.City;
import tomsung.cloud.agdc.bean.Crop;
import tomsung.cloud.agdc.bean.CropStep;
import tomsung.cloud.agdc.bean.CropStepInfo;
import tomsung.cloud.agdc.bean.CropType;
import tomsung.cloud.agdc.bean.GreenHouse;
import tomsung.cloud.agdc.bean.PlantModel;
import tomsung.cloud.agdc.bean.Province;
import tomsung.cloud.agdc.common.Const;
import tomsung.cloud.agdc.model.JsonObject;
import tomsung.cloud.agdc.model.JsonRequest;
import tomsung.cloud.agdc.model.JsonResponse;
import tomsung.cloud.agdc.service.CityService;
import tomsung.cloud.agdc.service.CropStepInfoService;
import tomsung.cloud.agdc.service.CropStepService;
import tomsung.cloud.agdc.service.CropTypeService;
import tomsung.cloud.agdc.service.GreenHouseService;
import tomsung.cloud.agdc.service.PlantModelService;
import tomsung.cloud.agdc.service.ProvinceService;

/**
 * 作物相关Controller
 * 
 * @author MiJunQiang
 *
 */
@Controller
public class CropController extends CommonController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private CropStepService cropStepService;

	@Autowired
	private CropStepInfoService cropStepInfoService;

	@Autowired
	private CropTypeService cropTypeService;

	@Autowired
	private GreenHouseService greenHouseService;

	@Autowired
	private PlantModelService plantModelService;

	@Autowired
	private ProvinceService provinceService;

	@Autowired
	private CityService cityService;

	@ResponseBody
	@RequestMapping(value = "/crop", method = RequestMethod.POST)
	protected JsonObject transer(final HttpServletRequest request, @RequestBody JsonRequest req) {
		return super.transer(request, req);
	}
	
	@RequestMapping(value = "/crop/detail", method = RequestMethod.POST)
	protected ModelAndView newsdetail(final ModelAndView mav, @RequestBody Map<String,Integer> req) {
//		int cropID = req.get(Const.CROPID);
//		int cropType = req.get(Const.CROPTYPE);
//		int plantType = req.get(Const.PLANTTYPE);
//		PlantModel model = plantModelService.getPlantModels(cropID, cropType, plantType);
		// TODO
//		mav.setViewName(model.getPlanthtml());
		// 获取对应的数据，放入Mode，组装成jsp返回
		mav.setViewName("/app/cropdetail");
		return mav;
	}

	/**
	 * 获取所有作物信息
	 * 
	 * @return
	 */
	public JsonResponse GET_CROPS(JsonRequest req) {
		JsonResponse res = req.getRep();
		try {
			List<CropType> cropTypes = cropTypeService.getAllCropTypes();
			if (cropTypes != null) {
				res.V.put("ALLCROPS", cropTypes);
			} else {
				res.R = false;
			}
		} catch (Exception e) {
			res.R = false;
			logger.error(e.getMessage(), e);
		}
		return res;
	}

	public JsonResponse GET_CROP_STEP_ALL_INFO(JsonRequest req) {
		JsonResponse res = req.getRep();
		try {
			List<CropStep> infos = cropStepService.selectCropStepData();
			res.V.put("CROPSTEPALLINFOS", infos);
		} catch (Exception e) {
			res.R = false;
			logger.error(e.getMessage(), e);
		}
		return res;
	}

	public JsonResponse GET_CROP_STEP_INFO(JsonRequest req) {
		JsonResponse res = req.getRep();
		try {
			int plantType = (Integer) req.V.get(Const.PLANTTYPE);
			List<CropStepInfo> infos = cropStepInfoService.selectCropStepData(plantType);
			res.V.put("CROPSTEPINFOS", infos);
		} catch (Exception e) {
			res.R = false;
			logger.error(e.getMessage(), e);
		}
		return res;
	}

	/**
	 * 获取大棚的农作物信息
	 * 
	 * @return
	 */
	public JsonResponse GET_CROPS_BY_GREENHOUSEID(JsonRequest req) {
		JsonResponse res = req.getRep();
		try {
			Integer greenhouseId = (Integer) req.V.get(Const.GREENHOUSEID);
			GreenHouse house = greenHouseService.selectGreenHouse(greenhouseId);
			if (house != null) {
				Crop crop = house.getCrop();
				CropType cropType = cropTypeService.selectCropType(crop.getCropId());
				res.V.put("CROP", crop);
				res.V.put("CROPTYPE", cropType);
			} else {
				res.R = false;
				res.setErrorMsg("获取农作物信息失败。");
			}
		} catch (Exception e) {
			res.R = false;
			logger.error(e.getMessage(), e);
		}

		return res;
	}

	/**
	 * 获取大棚信息
	 * 
	 * @param req
	 * @return
	 */
	public JsonResponse GET_GREENHOUSE(JsonRequest req) {
		JsonResponse res = req.getRep();
		try {
			Integer greenhouseId = (Integer) req.V.get(Const.GREENHOUSEID);
			GreenHouse h = greenHouseService.selectGreenHouse(greenhouseId);
			if (h == null) {
				h = new GreenHouse();
			}
			res.V.put("GREENHOUSE", h);
		} catch (Exception e) {
			res.R = false;
			logger.error(e.getMessage(), e);
		}
		return res;
	}

	/**
	 * 获取所有大棚信息
	 * 
	 * @param req
	 * @return
	 */
	public JsonResponse GET_ALL_GREENHOUSE(JsonRequest req) {
		JsonResponse res = req.getRep();
		try {
			List<GreenHouse> houses = greenHouseService.selectALLGreenHouse();
			if (houses != null) {
				res.V.put("GREENHOUSES", houses);
			}
			else
			{
				res.V.put("GREENHOUSES",new GreenHouse());
				logger.warn("there is no greenhouse.");
			}
		} catch (Exception e) {
			res.R = false;
			logger.error(e.getMessage(), e);
		}
		return res;
	}

	public JsonResponse GET_GREENHOUSE_BYADD(JsonRequest req) {
		JsonResponse res = req.getRep();
		try {
			Integer province = Integer.valueOf((String) req.V.get("PROVINCE"));
			Integer city = Integer.valueOf((String) req.V.get("CITY"));
			Integer district = Integer.valueOf((String) req.V.get("DISTRICT"));
			List<GreenHouse> houses = greenHouseService.getGreenHouseDataByAdd(province, city, district);
			if (houses == null || houses.size() <= 0) {
				res.R = false;
				res.setErrorMsg("获取大棚数据失败[%d]", houses);
			} else {
				List<Province> provinces = provinceService.getProvincesByIds(getProIds(houses));
				if (province == null && city == null && district == null) {
					res.V.put("PROVINCES", provinces);

				} else if (province != null && city == null && district == null) {
					for (Province pro : provinces) {
						if (pro.getProvinceid() == province) {
							res.V.put("CITYS", pro.getCitys());
							break;
						}
					}
				} else if (province != null && city != null && district == null) {
					for (Province pro : provinces) {
						if (pro.getProvinceid() == province) {
							List<City> citys = pro.getCitys();
							for (City c : citys) {
								if (c.getId() == city) {
									City cs = cityService.selectCity(city, c.getProvinceid());
									res.V.put("DISTIRCTS", cs.getDistricts());
									break;
								}
							}
						}
					}
				} else if (province != null && city != null && district != null) {
					res.V.put("GREENHOUSES", houses);
				}
			}
		} catch (Exception e) {
			res.R = false;
			logger.error(e.getMessage(), e);
			res.setErrorMsg("获取大棚数据失败.");
		}
		return res;
	}

	private List<Integer> getProIds(List<GreenHouse> houses) {
		Set<Integer> proIds = new HashSet<Integer>();
		for (GreenHouse house : houses) {
			proIds.add(house.getHouseAddPro());
		}
		return new ArrayList<Integer>(proIds);
	}

	public JsonResponse QUERY_CROPSTEP(JsonRequest req) {
		JsonResponse res = req.getRep();
		try {
			Integer greenhouseId = (Integer) req.V.get(Const.GREENHOUSEID);
			GreenHouse house = greenHouseService.selectGreenHouse(greenhouseId);
			if (house != null) {
				Map<String, Object> crop = new HashMap<>();
				List<Map<String, Object>> crops = new LinkedList<>();
				crops.add(crop);
				List<CropStep> steps = cropStepService.selectCropStepData(house.getCrop().getCropId(),
						house.getCrop().getCropType(), house.getGrowType());
				crop.put("CROPSTEPINFOS", steps);
				crop.put("CROPNAME", house.getCrop().getCropName());
				crop.put("PLANTTIME", house.getPlantTime());
				res.V.put("CROPS", crops);
			} else {
				res.R = false;
				res.setErrorMsg("查询作物生长周期失败。");
			}
		} catch (Exception e) {
			res.R = false;
			logger.error(e.getMessage(), e);
			res.setErrorMsg("查询作物生长周期失败。");
		}
		return res;
	}
}
